﻿using System;
namespace ACSR.Core.System
{
    /// <summary>
    /// A cached value holder, writes once read many
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class CachedValue<T>
    {
        private Func<T> _Resolver;
        bool _IsResolved = false;
        private T _Value;
        private Action<T> _Setter;

        /// <summary>
        /// Initializes a new instance of the <see cref="CachedValue&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="resolver">The resolver.</param>
        public CachedValue(Func<T> resolver)
            : this(resolver, null)
        {
            this._Resolver = resolver;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CachedValue&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="resolver">The resolver.</param>
        /// <param name="setter">The setter.</param>
        public CachedValue(Func<T> resolver, Action<T> setter)
        {
            this._Resolver = resolver;
            this._Setter = setter;
        }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        /// <value>The value.</value>
        public T Value
        {
            get
            {
                if (!_IsResolved)
                {
                    this._Value = this._Resolver();
                }

                return this._Value;
            }

            set
            {
                if (this._Setter != null)
                {
                    this._Setter(value);
                    this._IsResolved = false;
                }
                this._Value = value;
            }
        }
    }
}
